import os
import subprocess
from typing import Dict, Optional
from datetime import datetime
from utils.logger import logger

class FastlaneService:
    """Fastlane 服务"""
    
    def __init__(self, workspace_path: str, mock_mode: bool = False):
        """
        初始化 Fastlane 服务
        
        Args:
            workspace_path: 工作目录路径
            mock_mode: 是否使用模拟数据模式
        """
        logger.info(f"初始化 Fastlane 服务 (workspace_path: {workspace_path}, mock_mode: {mock_mode})")
        self.workspace_path = workspace_path
        self.mock_mode = mock_mode

    def _run_command(self, command: str) -> Dict:
        """
        执行命令
        
        Args:
            command: 要执行的命令
            
        Returns:
            包含执行结果的字典
        """
        logger.debug(f"执行命令: {command}")
        if self.mock_mode:
            return {
                'success': True,
                'output': f"Mock command executed: {command}",
                'error': None
            }

        try:
            result = subprocess.run(
                command,
                shell=True,
                cwd=self.workspace_path,
                capture_output=True,
                text=True
            )
            
            if result.returncode == 0:
                logger.debug("命令执行成功")
                return {
                    'success': True,
                    'output': result.stdout,
                    'error': None
                }
            else:
                logger.error(f"命令执行失败: {result.stderr}")
                return {
                    'success': False,
                    'output': None,
                    'error': result.stderr
                }
        except Exception as e:
            logger.error(f"命令执行异常: {str(e)}", exc_info=True)
            return {
                'success': False,
                'output': None,
                'error': str(e)
            }

    def download_metadata(self, username: str, bundle_id: str, output_path: Optional[str] = None) -> Dict:
        """
        下载metadata
        
        Args:
            username: Apple ID用户名
            bundle_id: 应用的Bundle ID
            output_path: 输出路径（可选）
            
        Returns:
            下载结果字典
        """
        logger.info(f"开始下载metadata (username: {username}, bundle_id: {bundle_id})")
        if self.mock_mode:
            metadata_path = output_path or os.path.join(self.workspace_path, 'metadata')
            logger.debug("使用模拟数据模式")
            return {
                'success': True,
                'metadata_path': metadata_path,
                'timestamp': datetime.now().isoformat()
            }

        try:
            # 如果指定了输出路径，确保目录存在
            if output_path:
                os.makedirs(output_path, exist_ok=True)
                metadata_path = output_path
            else:
                metadata_path = os.path.join(self.workspace_path, 'metadata')
            
            command = f"fastlane deliver download_metadata -u {username} -a {bundle_id}"
            if output_path:
                command += f" -m {output_path}"
            
            result = self._run_command(command)
            
            if result['success']:
                logger.info("metadata下载成功")
                return {
                    'success': True,
                    'metadata_path': metadata_path,
                    'timestamp': datetime.now().isoformat()
                }
            else:
                logger.error("metadata下载失败")
                return {
                    'success': False,
                    'error': result['error']
                }
                
        except Exception as e:
            logger.error(f"metadata下载异常: {str(e)}", exc_info=True)
            return {
                'success': False,
                'error': str(e)
            }

    def upload_metadata(self, username: str, bundle_id: str, version: str, 
                       metadata_path: str, skip_binary: bool = True) -> Dict:
        """
        上传metadata
        
        Args:
            username: Apple ID用户名
            bundle_id: 应用的Bundle ID
            version: 版本号
            metadata_path: metadata文件路径
            skip_binary: 是否跳过二进制文件上传
            
        Returns:
            上传结果字典
        """
        logger.info(f"开始上传metadata (username: {username}, bundle_id: {bundle_id}, version: {version})")
        if self.mock_mode:
            logger.debug("使用模拟数据模式")
            return {
                'success': True,
                'version': version,
                'timestamp': datetime.now().isoformat()
            }

        try:
            command = f"fastlane deliver -u {username} -a {bundle_id} -z {version} -m {metadata_path}"
            if skip_binary:
                command += " --skip_binary_upload --skip_screenshots"
            
            result = self._run_command(command)
            
            if result['success']:
                logger.info("metadata上传成功")
                return {
                    'success': True,
                    'version': version,
                    'timestamp': datetime.now().isoformat()
                }
            else:
                logger.error("metadata上传失败")
                return {
                    'success': False,
                    'error': result['error']
                }
                
        except Exception as e:
            logger.error(f"metadata上传异常: {str(e)}", exc_info=True)
            return {
                'success': False,
                'error': str(e)
            }

    def validate_metadata(self, metadata_path: str) -> Dict:
        """
        验证metadata文件
        
        Args:
            metadata_path: metadata文件路径
            
        Returns:
            验证结果字典
        """
        logger.info(f"开始验证metadata (metadata_path: {metadata_path})")
        if self.mock_mode:
            logger.debug("使用模拟数据模式")
            return {
                'success': True,
                'message': "Mock validation passed"
            }

        required_files = ['metadata.json', 'release_notes.txt']
        missing_files = []
        
        for file in required_files:
            if not os.path.exists(os.path.join(metadata_path, file)):
                missing_files.append(file)
        
        if missing_files:
            logger.error(f"缺少必要文件: {', '.join(missing_files)}")
            return {
                'success': False,
                'error': f"Missing required files: {', '.join(missing_files)}"
            }
            
        logger.info("metadata文件验证成功")
        return {
            'success': True,
            'message': "All required metadata files present"
        }
